﻿using UnityEngine;

public class Singleton<T> : Singleton where T: Singleton<T>
{
    protected static T _instance;

    public static T Instance
    {
        get
        {
            if (!Application.isPlaying)
            {
                return Resources.Load<T>(typeof(T).Name);
            }
            if (Singleton.applicationIsQuitting)
            {
                return null;
            }
            if (Singleton<T>._instance == null)
            {
                Singleton<T>._instance = (T) Object.FindObjectOfType(typeof(T));
                if (Singleton<T>._instance == null)
                {
                    T original = Resources.Load<T>(typeof(T).Name);
                    if (original != null)
                    {
                        Singleton<T>._instance = Object.Instantiate<T>(original);
                    }
                    else
                    {
                        Singleton<T>._instance = new GameObject().AddComponent<T>();
                    }
                    Singleton<T>._instance.name = typeof(T).Name;
                    if (!typeof(T).IsPublic)
                    {
                        Singleton<T>._instance.gameObject.hideFlags = HideFlags.HideInHierarchy;
                    }
                    Object.DontDestroyOnLoad(Singleton<T>._instance.gameObject);
                }
            }
            return Singleton<T>._instance;
        }
    }
}

